<template>
  <div class="mySelfData-myself">
    <div class="mySelfData-myself-center">
      <!-- <div class="section-title">聊天记录</div> -->

      <!-- 筛选条件区域 -->
      <div class="chat-filter-bar">
        <!-- 快速筛选标签 -->
        <div class="filter-tags">
          <div class="filter-tag" :class="{ active: chatSearchForm.dateTime }" @click="toggleDateFilter">
            <el-icon><Calendar /></el-icon>
            <span>{{ chatSearchForm.dateTime || '日期' }}</span>
            <el-icon v-if="chatSearchForm.dateTime" class="close-icon" @click.stop="clearDateFilter"><Close /></el-icon>
          </div>

          <div class="filter-tag" :class="{ active: chatSearchForm.message_type !== undefined }" @click="toggleTypeFilter">
            <el-icon><Document /></el-icon>
            <span>{{ getMessageTypeText(chatSearchForm.message_type) || '类型' }}</span>
            <el-icon v-if="chatSearchForm.message_type !== undefined" class="close-icon" @click.stop="clearTypeFilter"><Close /></el-icon>
          </div>

          <div class="filter-tag" :class="{ active: chatSearchForm.message_content }" @click="toggleContentFilter">
            <el-icon><Search /></el-icon>
            <span>{{ chatSearchForm.message_content || '搜索' }}</span>
            <el-icon v-if="chatSearchForm.message_content" class="close-icon" @click.stop="clearContentFilter"><Close /></el-icon>
          </div>
        </div>

        <!-- 清除所有筛选 -->
        <div v-if="hasActiveFilters" class="clear-all" @click="resetChatSearch">
          <el-icon><Close /></el-icon>
          <span>清除</span>
        </div>
      </div>

      <!-- 筛选面板 -->
      <div v-show="showFilterPanel" class="filter-panel">
        <div class="filter-content">
          <!-- 日期选择 -->
          <div v-if="activeFilter === 'date'" class="filter-section">
            <div class="filter-title">选择日期</div>
            <el-date-picker
              v-model="chatSearchForm.dateTime"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              size="small"
              @change="handleChatSearch"
            />
          </div>

          <!-- 消息类型选择 -->
          <div v-if="activeFilter === 'type'" class="filter-section">
            <div class="filter-title">消息类型</div>
            <div class="type-options">
              <div
                v-for="option in messageTypeOptions"
                :key="option.value"
                class="type-option"
                :class="{ active: chatSearchForm.message_type === option.value }"
                @click="selectMessageType(option.value)"
              >
                <el-icon><component :is="option.icon" /></el-icon>
                <span>{{ option.label }}</span>
              </div>
            </div>
          </div>

          <!-- 内容搜索 -->
          <div v-if="activeFilter === 'content'" class="filter-section">
            <div class="filter-title">搜索内容</div>
            <el-input v-model="chatSearchForm.message_content" placeholder="输入关键词" clearable size="small" @input="handleChatSearch" />
          </div>
        </div>
      </div>

      <div ref="chatHistoryScrollRef" class="chat-history-container" @scroll="handleChatHistoryScroll">
        <!-- 加载更多历史消息指示器 -->
        <div v-if="chatHistoryLoading && chatHistoryHasMore" class="loading-more-history">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>正在加载历史消息...</span>
        </div>
        <!-- 加载失败重试 -->
        <div v-else-if="chatHistoryLoadError && chatHistoryHasMore" class="load-error-history">
          <span>加载失败</span>
          <el-button type="text" size="small" @click="retryChatHistoryLoad">点击重试</el-button>
        </div>
        <!-- 没有更多消息提示 -->
        <div v-else-if="!chatHistoryHasMore && chatHistoryHasTriedLoadMore && chatHistoryMessages.length > 0" class="no-more-messages-history">
          <span>已显示全部消息</span>
        </div>

        <!-- 初始加载状态 -->
        <div v-if="chatHistoryLoading && chatHistoryMessages.length === 0" class="chat-history-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载聊天记录中...</span>
        </div>

        <!-- 聊天记录列表 -->
        <div v-else-if="chatHistoryMessages.length > 0" class="chat-history-messages">
          <div v-for="(message, index) in chatHistoryMessages" :key="message.id || index" class="chat-history-item">
            <div class="chat-history-time" v-if="message.message_create_time_str">{{ message.message_create_time_str }}</div>
            <div class="chat-history-content" :class="message.direction === 'right' ? 'right' : 'left'">
              <div class="chat-history-avatar">
                <img :src="message.senderUrl" alt="" />
              </div>
              <div class="chat-history-message">
                <div v-if="message.message_type == 1" v-html="formatMessageContent(message.message_content)"></div>
                <div v-if="message.message_type == 2" class="chat-history-image">
                  <el-image :preview-src-list="[imageUrlfirst + message.message_content]" :src="imageUrlfirst + message.message_content" />
                </div>
                <!-- 视频消息展示 -->
                <div v-if="message.message_type == 4" class="chat-history-video">
                  <video :src="imageUrlfirst + message.message_content" controls style="max-width: 200px; max-height: 200px"></video>
                </div>
                <!-- 语音消息展示 -->
                <div v-if="message.message_type == 3" class="chat-history-audio">
                  <div class="audio-container" :class="message.direction === 'right' ? 'right' : 'left'">
                    <audio :src="imageUrlfirst + message.message_content" controls></audio>

                    <el-tooltip :content="message.transcribedText ? '收起文字' : '转文字'" placement="top">
                      <el-button type="primary" size="small" class="transcribe-btn" :loading="message.transcribing" @click="handleTranscribeAudio(message)">
                        <el-icon><Switch /></el-icon>
                      </el-button>
                    </el-tooltip>
                  </div>
                  <div v-if="message.transcribedText" class="transcribed-text">
                    <div class="transcribed-label">转文字结果：</div>
                    <div class="transcribed-content">{{ message.transcribedText }}</div>
                  </div>
                </div>
                <!-- 文件消息展示 -->
                <div v-if="message.message_type == 5" class="chat-history-file">
                  <div class="file-container" :class="message.direction === 'right' ? 'right' : 'left'" @click="handleDownloadFile(message)">
                    <div class="file-icon">
                      <el-icon size="24"><Document /></el-icon>
                    </div>
                    <div class="file-info">
                      <div class="file-name">{{ message.media_file_id || '未知文件' }}</div>
                    </div>
                    <div class="download-icon">
                      <el-icon size="16"><Download /></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态显示 -->
        <div v-else class="chat-history-empty">
          <el-empty description="暂无聊天记录" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Loading, Switch, Document, Download, Search, ArrowDown, Calendar, Close } from '@element-plus/icons-vue';

// Props
interface Props {
  msgprofilewx_id: string;
  messageContent: any;
  nowExprentTag: string;
  imageUrlfirst: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  transcribeAudio: [message: any];
  downloadFile: [message: any];
  msgSendMessages: [params: any];
}>();

// 聊天记录查询相关数据
const showFilterPanel = ref(false); // 控制筛选面板显示/隐藏
const activeFilter = ref(''); // 当前激活的筛选类型
const chatSearchForm = reactive({
  dateTime: '',
  message_type: undefined as number | undefined,
  message_content: ''
});

// 消息类型选项
const messageTypeOptions = [
  { label: '纯文本', value: 1, icon: 'Document' },
  { label: '图片', value: 2, icon: 'Picture' },
  { label: '音频', value: 3, icon: 'Microphone' },
  { label: '视频', value: 4, icon: 'VideoPlay' },
  { label: '文件', value: 5, icon: 'Document' }
];

// 计算是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return chatSearchForm.dateTime || chatSearchForm.message_type !== undefined || chatSearchForm.message_content;
});

// 获取消息类型文本
const getMessageTypeText = (type: number | undefined) => {
  const option = messageTypeOptions.find((opt) => opt.value === type);
  return option ? option.label : '';
};

// 切换筛选面板
const toggleFilterPanel = (filterType: string) => {
  if (activeFilter.value === filterType) {
    showFilterPanel.value = false;
    activeFilter.value = '';
  } else {
    activeFilter.value = filterType;
    showFilterPanel.value = true;
  }
};

// 各种筛选切换函数
const toggleDateFilter = () => toggleFilterPanel('date');
const toggleTypeFilter = () => toggleFilterPanel('type');
const toggleContentFilter = () => toggleFilterPanel('content');

// 清除各种筛选
const clearDateFilter = () => {
  chatSearchForm.dateTime = '';
  handleChatSearch();
};

const clearTypeFilter = () => {
  chatSearchForm.message_type = undefined;
  handleChatSearch();
};

const clearContentFilter = () => {
  chatSearchForm.message_content = '';
  handleChatSearch();
};

// 选择消息类型
const selectMessageType = (type: number) => {
  chatSearchForm.message_type = type;
  handleChatSearch();
  showFilterPanel.value = false;
  activeFilter.value = '';
};

// 聊天记录数据
const chatHistoryMessages = ref<any[]>([]);
const chatHistoryLoading = ref(false);
const chatHistoryHasMore = ref(true);
const chatHistoryCurrent = ref('1');
const chatHistorySize = ref('30');
const chatHistoryLoadError = ref(false);
const chatHistoryHasTriedLoadMore = ref(false);
const chatHistoryScrollRef = ref<HTMLElement | null>(null);

// 聊天记录滚动防抖定时器
let chatHistoryScrollTimeout: NodeJS.Timeout | null = null;

// 格式化消息内容
const formatMessageContent = (content: any) => {
  return content.replace(/\n/g, '<br>');
};

// 处理音频转文字
const handleTranscribeAudio = (message: any) => {
  emit('transcribeAudio', message);
};

// 处理文件下载
const handleDownloadFile = (message: any) => {
  emit('downloadFile', message);
};

// 聊天记录查询
const handleChatSearch = () => {
  chatHistoryCurrent.value = '1';
  chatHistoryHasMore.value = true;
  chatHistoryLoading.value = true;
  chatHistoryLoadError.value = false;
  chatHistoryHasTriedLoadMore.value = false;

  let params: any = {
    wxId: props.msgprofilewx_id,
    current: chatHistoryCurrent.value,
    size: chatHistorySize.value,
    ...(props.nowExprentTag === '群聊' ? { group_id: props.messageContent.group_id } : { sendWxId: props.messageContent.wx_id })
  };

  // 添加查询条件
  if (chatSearchForm.dateTime) {
    params.dateTime = chatSearchForm.dateTime;
  }
  if (chatSearchForm.message_type !== undefined && chatSearchForm.message_type !== null) {
    params.message_type = chatSearchForm.message_type;
  }
  if (chatSearchForm.message_content) {
    params.message_content = chatSearchForm.message_content;
  }

  emit('msgSendMessages', params);
};

// 重置查询条件
const resetChatSearch = () => {
  chatSearchForm.dateTime = '';
  chatSearchForm.message_type = undefined;
  chatSearchForm.message_content = '';
  loadChatHistory();
};

// 加载聊天记录
const loadChatHistory = () => {
  chatHistoryCurrent.value = '1';
  chatHistoryHasMore.value = true;
  chatHistoryLoading.value = true;
  chatHistoryLoadError.value = false;
  chatHistoryHasTriedLoadMore.value = false;

  let params: any = {
    wxId: props.msgprofilewx_id,
    current: chatHistoryCurrent.value,
    size: chatHistorySize.value,
    ...(props.nowExprentTag === '群聊' ? { group_id: props.messageContent.group_id } : { sendWxId: props.messageContent.wx_id })
  };

  emit('msgSendMessages', params);
};

// 聊天记录滚动到底部
const scrollChatHistoryToBottom = () => {
  if (chatHistoryScrollRef.value) {
    chatHistoryScrollRef.value.scrollTop = chatHistoryScrollRef.value.scrollHeight;
  }
};

// 聊天记录滚动处理
const handleChatHistoryScroll = () => {
  if (chatHistoryScrollTimeout) {
    clearTimeout(chatHistoryScrollTimeout);
  }

  chatHistoryScrollTimeout = setTimeout(() => {
    if (!chatHistoryScrollRef.value || chatHistoryLoading.value || !chatHistoryHasMore.value) return;

    const { scrollTop } = chatHistoryScrollRef.value;
    if (scrollTop <= 50) {
      loadMoreChatHistory();
    }
  }, 100);
};

// 加载更多聊天记录
const loadMoreChatHistory = async () => {
  if (chatHistoryLoading.value || !chatHistoryHasMore.value) return;

  chatHistoryLoading.value = true;
  chatHistoryLoadError.value = false;
  chatHistoryHasTriedLoadMore.value = true;
  chatHistoryCurrent.value = (parseInt(chatHistoryCurrent.value) + 1).toString();

  try {
    let params: any = {
      wxId: props.msgprofilewx_id,
      current: chatHistoryCurrent.value,
      size: chatHistorySize.value,
      ...(props.nowExprentTag === '群聊' ? { group_id: props.messageContent.group_id } : { sendWxId: props.messageContent.wx_id })
    };

    // 添加查询条件
    if (chatSearchForm.dateTime) {
      params.dateTime = chatSearchForm.dateTime;
    }
    if (chatSearchForm.message_type !== undefined && chatSearchForm.message_type !== null) {
      params.message_type = chatSearchForm.message_type;
    }
    if (chatSearchForm.message_content) {
      params.message_content = chatSearchForm.message_content;
    }

    emit('msgSendMessages', params);
  } catch (error) {
    console.error('加载更多聊天记录失败:', error);
    ElMessage.error('加载更多聊天记录失败');
    chatHistoryLoadError.value = true;
    chatHistoryCurrent.value = (parseInt(chatHistoryCurrent.value) - 1).toString();
  } finally {
    chatHistoryLoading.value = false;
  }
};

// 重试加载聊天记录
const retryChatHistoryLoad = () => {
  loadMoreChatHistory();
};

// 暴露方法和数据给父组件
defineExpose({
  loadChatHistory,
  scrollChatHistoryToBottom,
  chatHistoryMessages,
  chatHistoryLoading,
  chatHistoryHasMore,
  chatHistoryCurrent,
  chatHistorySize,
  chatHistoryLoadError,
  chatHistoryHasTriedLoadMore,
  chatSearchForm,
  chatHistoryScrollRef
});
</script>
<style lang="scss" scoped>
@use '../weChat.scss';

// 全新的标签式筛选样式
.chat-filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 8px 0;

  .filter-tags {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;

    .filter-tag {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 4px 8px;
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 16px;
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 12px;
      color: #6c757d;
      user-select: none;

      &:hover {
        background: #e9ecef;
        border-color: #dee2e6;
      }

      &.active {
        background: #e3f2fd;
        border-color: #2196f3;
        color: #1976d2;
      }

      .el-icon {
        font-size: 12px;
      }

      .close-icon {
        margin-left: 4px;
        padding: 1px;
        border-radius: 50%;

        &:hover {
          background: rgba(0, 0, 0, 0.1);
        }
      }
    }
  }

  .clear-all {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    background: #fff5f5;
    border: 1px solid #fed7d7;
    border-radius: 16px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 11px;
    color: #e53e3e;

    &:hover {
      background: #fed7d7;
      border-color: #feb2b2;
    }

    .el-icon {
      font-size: 11px;
    }
  }
}

.filter-panel {
  margin-bottom: 12px;
  padding: 12px;
  background: #ffffff;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  animation: slideDown 0.3s ease;

  .filter-content {
    .filter-section {
      .filter-title {
        font-size: 13px;
        color: #495057;
        margin-bottom: 8px;
        font-weight: 500;
      }

      .type-options {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;

        .type-option {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 6px 12px;
          background: #f8f9fa;
          border: 1px solid #e9ecef;
          border-radius: 20px;
          cursor: pointer;
          transition: all 0.2s ease;
          font-size: 12px;
          color: #6c757d;

          &:hover {
            background: #e9ecef;
            border-color: #dee2e6;
          }

          &.active {
            background: #e3f2fd;
            border-color: #2196f3;
            color: #1976d2;
          }

          .el-icon {
            font-size: 12px;
          }
        }
      }
    }
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
